package com.iedu.demo.lgq.service.impl;

import com.iedu.demo.lgq.entity.TbCart;
import com.iedu.demo.lgq.mapper.CartMapper;
import com.iedu.demo.lgq.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    @Override
    public boolean addToCart(TbCart cart) {
        // 检查数据库中是否已有该商品
        TbCart existingCart = cartMapper.findCartByUserNameAndItemId(cart.getUserName(), cart.getItemId());

        if (existingCart != null) {
            // 如果商品已存在，更新数量
            existingCart.setQuantity(existingCart.getQuantity() + 1);
            cartMapper.updateCart(existingCart);
            return false; // 表示购物车中已有商品，数量已增加
        } else {
            // 如果商品不存在，新增购物车记录
            cartMapper.insertCart(cart);
            return true; // 表示商品已成功添加到购物车
        }
    }

    @Override
    public List<TbCart> getCartItems(String userName) {
        return cartMapper.getCartItemsByUserName(userName);
    }

    @Override
    public boolean updateCartItemQuantity(Long id, int quantity) {
        int rowsAffected = cartMapper.updateCartItemQuantity(id, quantity);
        return rowsAffected > 0;
    }

    @Override
    public boolean deleteCartItem(Long id) {
        int rowsAffected = cartMapper.deleteCartItem(id);
        return rowsAffected > 0;
    }

    @Override
    public boolean batchDeleteCartItems(List<Long> ids) {
        int rowsAffected = cartMapper.batchDeleteCartItems(ids);
        return rowsAffected > 0;
    }

    @Override
    public boolean purchaseCartItem(Long id) {
        int rowsAffected = cartMapper.purchaseCartItem(id);
        return rowsAffected > 0;
    }

    @Override
    public boolean batchPurchaseCartItems(List<Long> ids) {
        for (Long id : ids) {
            purchaseCartItem(id);  // 执行单项购买
        }
        return true;
    }
}
